package com.chs.recoginition.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.validation.ConstraintViolation;
import java.util.List;
import java.util.Set;


@Slf4j
public class ValidatorUtils {
    public static <T> String getErrorMessage(Set<? extends ConstraintViolation<?>> constraintViolationSet) {
        StringBuilder msg = new StringBuilder();
        for (ConstraintViolation<?> constraintViolation : constraintViolationSet) {
            // 读取参数字段，constraintViolation.getMessage() 读取验证注解中的message值
            PathImpl pathImpl = (PathImpl) constraintViolation.getPropertyPath();
            String paramName = pathImpl.getLeafNode().getName();
            String message = "参数{" + paramName + "}" + constraintViolation.getMessage();
            log.debug("{} -> {} -> {}", constraintViolation.getRootBeanClass().getName(), pathImpl.toString(), message);
            msg.append(",");
            msg.append(constraintViolation.getMessage());
        }
        return msg.length() == 0 ? null : msg.substring(1);
    }

    public static String getErrorMessage(BindingResult bindingResult) {
        StringBuilder msg = new StringBuilder();
        List<ObjectError> errors = bindingResult.getAllErrors();
        for (ObjectError error : errors) {
            msg.append(",");
            msg.append(error.getDefaultMessage());
        }

        return msg.substring(1);
    }
}
